<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        <button></button>
        <button></button>
        <button></button>
    </div>
</body>
<script>
    // 1- ref是一个函数
    // 2- ref返回的是一个RefImpl的实例
    // 3- RefImpl拥有属性value
    // 4- ref可以接收基本数据类型以及引用类型
    //    4-1- 如果接收的是基本数据类型，value的值即是该基本数据类型的值
    //    4-2- 如果接收的是引用数据类型，value的值Proxy实例
    const reactive = function(obj){
        return new Proxy(obj,{
            get(target,key){
                return target[key];
            },
            set(target,key,newValue){
                if(key === "age"){
                    target[key] = btns[2].innerText =  newValue;
                }else{
                    target[key] = btns[1].innerText =  newValue;
                }

            }
        })
    }
    const RefImpl = function(arg){
        if(typeof arg === "object"){
            this.value = reactive(arg);
            // this.value = new Proxy(arg,{
            //     get(target,key){
            //         return target[key];
            //     },
            //     set(target,key,newValue){
            //         target[key] = btns[1].innerText =  newValue;
            //     }
            // })
        }else{
            let _value = arg;
            Object.defineProperty(this,"value",{
                get(){
                    return _value;
                },
                set(v){
                    _value = btns[0].innerText =  v;
                }
            })
        }

    }
    function ref(arg){
        return new RefImpl(arg);
    }
    const num = ref(10);
    const info = ref({
        userName:"zhangsan"
    })
    const obj = reactive({
        age:100
    })
    const btns = document.querySelectorAll("button");
    btns[0].innerText = num.value;
    btns[1].innerText = info.value.userName;
    btns[2].innerText =obj.age;
    btns[0].onclick = function(){
        num.value += 1;
    }
    btns[1].onclick = function(){
        info.value.userName += "!"
    }
    btns[2].onclick = function(){
        obj.age += 1;
    }
</script>
</html>